import os
from PySide6.QtCore import Qt, QSize, Signal, Slot, QTimer
from PySide6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                              QLabel, QSlider, QPushButton, QFileDialog, 
                              QMessageBox, QSplitter, QFrame, QGraphicsOpacityEffect,
                              QSizePolicy, QCheckBox, QProgressBar, QListWidget,
                              QTabWidget, QDialog, QDialogButtonBox, QGridLayout,
                              QSpinBox, QComboBox, QGroupBox)
from PySide6.QtGui import QPixmap, QImage, QFont, QIcon, QColor, QPalette

class ImageView(QWidget):
    """图片显示组件，用于显示原始图片或处理后的图片"""
    
    def __init__(self, title, parent=None):
        super().__init__(parent)
        self.title = title
        self.image = None
        self.init_ui()
        
    def init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)  # 减少内边距，使得两侧对齐
        
        # 标题和图片信息区域
        info_area = QWidget()
        info_layout = QVBoxLayout(info_area)
        info_layout.setContentsMargins(0, 0, 0, 0)
        
        # 标题标签
        self.title_label = QLabel(self.title)
        self.title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.title_label.setFont(QFont("Arial", 12, QFont.Weight.Bold))
        info_layout.addWidget(self.title_label)
        
        # 图片信息标签
        self.info_label = QLabel("未加载图片")
        self.info_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        info_layout.addWidget(self.info_label)
        
        layout.addWidget(info_area)
        
        # 创建图片显示区域
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.image_label.setMinimumSize(350, 350)
        self.image_label.setFrameShape(QFrame.Shape.Box)
        self.image_label.setStyleSheet("border: 1px solid #cccccc; background-color: #f5f5f5;")
        self.image_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        
        layout.addWidget(self.image_label, 1)
        
    def set_image(self, image):
        """设置要显示的图片
        
        Args:
            image: PIL.Image对象
        """
        self.image = image
        if image:
            # 更新信息标签
            self.info_label.setText(f"尺寸: {image.width}x{image.height} 像素")
            
            # 将PIL图像转换为QImage以在Qt中显示
            if image.mode == 'RGB':
                q_image = QImage(image.tobytes(), image.width, image.height, 
                                 3 * image.width, QImage.Format.Format_RGB888)
            elif image.mode == 'RGBA':
                q_image = QImage(image.tobytes(), image.width, image.height,
                                 4 * image.width, QImage.Format.Format_RGBA8888)
            else:
                # 对于其他模式，转换为RGB
                rgb_image = image.convert('RGB')
                q_image = QImage(rgb_image.tobytes(), rgb_image.width, rgb_image.height,
                                 3 * rgb_image.width, QImage.Format.Format_RGB888)
            
            # 创建QPixmap并显示
            pixmap = QPixmap.fromImage(q_image)
            
            # 缩放以适应显示区域
            self.image_label.setPixmap(pixmap.scaled(
                self.image_label.width(), self.image_label.height(),
                Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation
            ))
        else:
            self.info_label.setText("未加载图片")
            self.image_label.clear()
            
    def resizeEvent(self, event):
        """窗口大小变化时重新调整图像大小"""
        super().resizeEvent(event)
        if self.image and not self.image_label.pixmap().isNull():
            pixmap = QPixmap.fromImage(self.image_label.pixmap().toImage())
            self.image_label.setPixmap(pixmap.scaled(
                self.image_label.width(), self.image_label.height(),
                Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation
            ))


class SliderWithLabel(QWidget):
    """带有标签和数值显示的滑动条组件"""
    
    valueChanged = Signal(int)
    
    def __init__(self, title, min_value=0, max_value=255, default_value=128, parent=None):
        super().__init__(parent)
        self.title = title
        self.min_value = min_value
        self.max_value = max_value
        self.default_value = default_value
        self.init_ui()
        
    def init_ui(self):
        """初始化UI"""
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 标题标签
        title_label = QLabel(self.title)
        title_label.setMinimumWidth(20)
        layout.addWidget(title_label)
        
        # 滑动条
        self.slider = QSlider(Qt.Orientation.Horizontal)
        self.slider.setRange(self.min_value, self.max_value)
        self.slider.setValue(self.default_value)
        self.slider.setTickPosition(QSlider.TickPosition.TicksBelow)
        self.slider.setTickInterval(32)
        layout.addWidget(self.slider, 1)
        
        # 数值标签
        self.value_label = QLabel(f"{self.default_value}")
        self.value_label.setMinimumWidth(40)
        self.value_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
        layout.addWidget(self.value_label)
        
        # 连接信号和槽
        self.slider.valueChanged.connect(self.update_value)
        
    def update_value(self, value):
        """更新显示的值并发射信号"""
        self.value_label.setText(f"{value}")
        self.valueChanged.emit(value)
        
    def get_value(self):
        """获取当前值"""
        return self.slider.value()
        
    def set_value(self, value):
        """设置当前值"""
        self.slider.setValue(value)


class MainWindow(QMainWindow):
    """图片转换工具主窗口"""
    
    def __init__(self):
        super().__init__()
        self.image_processor = None  # 在设置UI后初始化
        self.init_ui()
        
    def init_ui(self):
        """初始化UI"""
        # 设置窗口基本属性
        self.setWindowTitle("TFT到OLED图片转换工具")
        self.resize(1000, 600)
        
        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建分割器，用于左右两侧的图片显示
        splitter = QSplitter(Qt.Orientation.Horizontal)
        splitter.setHandleWidth(1)
        
        # 左侧原始图片区域
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)
        left_layout.setContentsMargins(10, 10, 10, 10)
        
        # 右侧处理后图片区域
        right_panel = QWidget()
        right_layout = QVBoxLayout(right_panel)
        right_layout.setContentsMargins(10, 10, 10, 10)
        
        # 统一创建预览区域（保证尺寸一致）
        preview_splitter = QSplitter(Qt.Orientation.Horizontal)
        
        # 左侧图片预览
        self.original_image_view = ImageView("原始图片")
        preview_splitter.addWidget(self.original_image_view)
        
        # 右侧图片预览
        self.processed_image_view = ImageView("处理后图片")
        preview_splitter.addWidget(self.processed_image_view)
        
        # 设置预览区域等分
        preview_splitter.setSizes([500, 500])
        
        # 将预览区域添加到主分割器
        main_layout.addWidget(preview_splitter, 1)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        self.progress_bar.setVisible(False)
        main_layout.addWidget(self.progress_bar)
        
        # 批处理进度标签
        self.batch_label = QLabel("批处理进度: 0/0")
        self.batch_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.batch_label.setVisible(False)  # 初始状态隐藏
        main_layout.addWidget(self.batch_label)
        
        # 创建选项卡控件
        tabs = QTabWidget()
        
        # 单图处理选项卡
        single_tab = QWidget()
        single_layout = QHBoxLayout(single_tab)
        
        # 创建左侧控制面板
        left_control_panel = QWidget()
        left_control_layout = QVBoxLayout(left_control_panel)
        
        # RGB阈值调整区域
        thresholds_group = QGroupBox("RGB阈值设置")
        thresholds_layout = QVBoxLayout(thresholds_group)
        
        # 创建RGB滑动条，默认值设为128（255的一半）
        self.r_slider = SliderWithLabel("R", default_value=128)
        self.g_slider = SliderWithLabel("G", default_value=128)
        self.b_slider = SliderWithLabel("B", default_value=128)
        
        thresholds_layout.addWidget(self.r_slider)
        thresholds_layout.addWidget(self.g_slider)
        thresholds_layout.addWidget(self.b_slider)
        
        # 添加颜色反转复选框
        self.invert_checkbox = QCheckBox("颜色反转")
        self.invert_checkbox.setToolTip("反转黑白颜色，用于提取特定背景或内容")
        thresholds_layout.addWidget(self.invert_checkbox)
        
        # 添加RGB阈值区域到左侧控制面板
        left_control_layout.addWidget(thresholds_group)
        
        # 添加加载按钮
        self.load_button = QPushButton("加载图片")
        self.load_button.setMinimumHeight(40)
        left_control_layout.addWidget(self.load_button)
        
        # 添加左侧控制面板到单图处理选项卡
        single_layout.addWidget(left_control_panel)
        
        # 创建右侧控制面板
        right_control_panel = QWidget()
        right_control_layout = QVBoxLayout(right_control_panel)
        
        # 预处理选项
        preprocess_group = QGroupBox("图像预处理")
        preprocess_layout = QVBoxLayout(preprocess_group)
        
        # 调整大小选项
        resize_layout = QGridLayout()
        self.resize_checkbox = QCheckBox("调整大小")
        resize_layout.addWidget(self.resize_checkbox, 0, 0, 1, 2)
        
        resize_width_label = QLabel("宽度:")
        resize_layout.addWidget(resize_width_label, 1, 0)
        self.resize_width_spin = QSpinBox()
        self.resize_width_spin.setRange(8, 1024)
        self.resize_width_spin.setValue(128)
        resize_layout.addWidget(self.resize_width_spin, 1, 1)
        
        resize_height_label = QLabel("高度:")
        resize_layout.addWidget(resize_height_label, 2, 0)
        self.resize_height_spin = QSpinBox()
        self.resize_height_spin.setRange(8, 1024)
        self.resize_height_spin.setValue(64)
        resize_layout.addWidget(self.resize_height_spin, 2, 1)
        
        preprocess_layout.addLayout(resize_layout)
        
        # 旋转选项
        rotate_layout = QGridLayout()
        self.rotate_checkbox = QCheckBox("旋转")
        rotate_layout.addWidget(self.rotate_checkbox, 0, 0)
        
        self.rotate_combo = QComboBox()
        self.rotate_combo.addItems(["0°", "90°", "180°", "270°"])
        rotate_layout.addWidget(self.rotate_combo, 0, 1)
        
        preprocess_layout.addLayout(rotate_layout)
        
        # 翻转选项
        flip_layout = QHBoxLayout()
        self.flip_h_checkbox = QCheckBox("水平翻转")
        flip_layout.addWidget(self.flip_h_checkbox)
        
        self.flip_v_checkbox = QCheckBox("垂直翻转")
        flip_layout.addWidget(self.flip_v_checkbox)
        
        preprocess_layout.addLayout(flip_layout)
        
        # 添加预处理选项到右侧控制面板
        right_control_layout.addWidget(preprocess_group)
        
        # 导出按钮区域
        export_group = QGroupBox("导出选项")
        export_layout = QVBoxLayout(export_group)
        
        # 创建导出按钮
        export_buttons_layout = QHBoxLayout()
        self.export_bmp_button = QPushButton("导出BMP")
        self.export_c_button = QPushButton("导出C文件")
        
        self.export_bmp_button.setMinimumHeight(40)
        self.export_c_button.setMinimumHeight(40)
        
        export_buttons_layout.addWidget(self.export_bmp_button)
        export_buttons_layout.addWidget(self.export_c_button)
        export_layout.addLayout(export_buttons_layout)
        
        # 添加导出选项到右侧控制面板
        right_control_layout.addWidget(export_group)
        
        # 添加右侧控制面板到单图处理选项卡
        single_layout.addWidget(right_control_panel)
        
        # 批处理选项卡
        batch_tab = QWidget()
        batch_layout = QVBoxLayout(batch_tab)
        
        # 批处理文件列表
        self.batch_list = QListWidget()
        self.batch_list.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)
        batch_layout.addWidget(self.batch_list)
        
        # 批处理按钮区域
        batch_buttons_layout = QHBoxLayout()
        
        # 添加文件按钮
        self.add_files_button = QPushButton("添加文件")
        self.add_files_button.setMinimumHeight(40)
        batch_buttons_layout.addWidget(self.add_files_button)
        
        # 添加目录按钮
        self.add_dir_button = QPushButton("选择目录")
        self.add_dir_button.setMinimumHeight(40)
        self.add_dir_button.setToolTip("递归扫描目录中的所有BMP图片")
        batch_buttons_layout.addWidget(self.add_dir_button)
        
        # 清除列表按钮
        self.clear_list_button = QPushButton("清除列表")
        self.clear_list_button.setMinimumHeight(40)
        batch_buttons_layout.addWidget(self.clear_list_button)
        
        # 批量处理按钮
        self.process_batch_button = QPushButton("批量处理")
        self.process_batch_button.setMinimumHeight(40)
        batch_buttons_layout.addWidget(self.process_batch_button)
        
        # 批量导出按钮
        self.export_batch_button = QPushButton("批量导出")
        self.export_batch_button.setMinimumHeight(40)
        self.export_batch_button.setEnabled(False)  # 初始禁用
        batch_buttons_layout.addWidget(self.export_batch_button)
        
        batch_layout.addLayout(batch_buttons_layout)
        
        # 添加选项卡
        tabs.addTab(single_tab, "单图处理")
        tabs.addTab(batch_tab, "批量处理")
        
        main_layout.addWidget(tabs)
        
        # 状态栏
        self.status_bar = self.statusBar()
        self.status_bar.showMessage("就绪")
        
        # 连接信号和槽
        self.connect_signals()
        
        # 设置样式
        self.setup_styles()
        
    def setup_styles(self):
        """设置界面样式"""
        # 设置应用全局样式
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f0f0f0;
            }
            QLabel {
                color: #333333;
            }
            QPushButton {
                background-color: #4a86e8;
                color: white;
                border: none;
                border-radius: 4px;
                padding: 8px 16px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #3a76d8;
            }
            QPushButton:pressed {
                background-color: #2a66c8;
            }
            QSlider::groove:horizontal {
                border: 1px solid #bbb;
                height: 10px;
                border-radius: 4px;
                background: #f0f0f0;
            }
            QSlider::handle:horizontal {
                background: #4a86e8;
                border: 1px solid #777;
                width: 18px;
                margin: -2px 0;
                border-radius: 5px;
            }
            QStatusBar {
                background-color: #eaeaea;
                color: #333333;
            }
        """)
        
    def connect_signals(self):
        """连接信号和槽"""
        # 滑动条信号
        self.r_slider.valueChanged.connect(self.update_thresholds)
        self.g_slider.valueChanged.connect(self.update_thresholds)
        self.b_slider.valueChanged.connect(self.update_thresholds)
        
        # 颜色反转复选框信号
        self.invert_checkbox.stateChanged.connect(self.update_invert_colors)
        
        # 预处理信号
        self.resize_checkbox.stateChanged.connect(self.update_preprocess)
        self.resize_width_spin.valueChanged.connect(self.update_preprocess)
        self.resize_height_spin.valueChanged.connect(self.update_preprocess)
        self.rotate_checkbox.stateChanged.connect(self.update_preprocess)
        self.rotate_combo.currentIndexChanged.connect(self.update_preprocess)
        self.flip_h_checkbox.stateChanged.connect(self.update_preprocess)
        self.flip_v_checkbox.stateChanged.connect(self.update_preprocess)
        
        # 单图处理按钮信号
        self.load_button.clicked.connect(self.load_image)
        self.export_bmp_button.clicked.connect(self.export_bmp)
        self.export_c_button.clicked.connect(self.export_c_file)
        
        # 批处理按钮信号
        self.add_files_button.clicked.connect(self.add_batch_files)
        self.add_dir_button.clicked.connect(self.add_batch_directory)
        self.clear_list_button.clicked.connect(self.clear_batch_files)
        self.process_batch_button.clicked.connect(self.process_batch)
        self.export_batch_button.clicked.connect(self.export_batch)
        
    def set_image_processor(self, processor):
        """设置图像处理器"""
        self.image_processor = processor
        
        # 连接图像处理器的信号
        self.image_processor.signals.progress_changed.connect(self.update_progress)
        self.image_processor.signals.processing_finished.connect(self.processing_finished)
        self.image_processor.signals.processing_error.connect(self.processing_error)
        self.image_processor.signals.batch_progress_changed.connect(self.update_batch_progress)
        self.image_processor.signals.batch_processing_finished.connect(self.batch_processing_finished)
        self.image_processor.signals.batch_processing_error.connect(self.batch_processing_error)
        
    def update_progress(self, value):
        """更新进度值
        
        Args:
            value (int): 进度值(0-100)
        """
        # 如果进度为0或100，则更新状态栏
        if value == 0:
            self.status_bar.showMessage("开始处理图像...")
        elif value == 100:
            self.status_bar.showMessage("图像处理完成")
            
    def update_batch_progress(self, current, total):
        """更新批处理进度
        
        Args:
            current (int): 当前处理的图像索引
            total (int): 总图像数量
        """
        self.status_bar.showMessage(f"批处理进度: {current}/{total}")
            
    def processing_finished(self, processed_image):
        """图像处理完成回调
        
        Args:
            processed_image: 处理后的图像
        """
        # 显示处理后的图像
        self.processed_image_view.set_image(processed_image)
        
        # 启用UI控件
        self.enable_ui_controls(True)
        
        # 创建渐变动画效果
        self.animate_image_change()
        
    def batch_processing_finished(self, processed_images):
        """批处理完成回调
        
        Args:
            processed_images (list): 处理后的图像列表
        """
        # 启用UI控件
        self.enable_ui_controls(True)
        
        # 启用批量导出按钮
        self.export_batch_button.setEnabled(True)
        
        # 更新状态栏
        self.status_bar.showMessage(f"批处理完成，共处理 {len(processed_images)} 张图片")
        
    def batch_processing_error(self, error_message, index):
        """批处理错误回调
        
        Args:
            error_message (str): 错误信息
            index (int): 错误的图像索引
        """
        # 更新状态栏
        self.status_bar.showMessage(f"批处理错误: {error_message}")
        
    def processing_error(self, error_message):
        """图像处理错误回调
        
        Args:
            error_message (str): 错误信息
        """
        # 显示错误信息
        QMessageBox.critical(self, "处理错误", error_message)
        
        # 启用UI控件
        self.enable_ui_controls(True)
        
    def enable_ui_controls(self, enabled):
        """启用或禁用UI控件
        
        Args:
            enabled (bool): True为启用，False为禁用
        """
        # 设置滑动条状态
        self.r_slider.setEnabled(enabled)
        self.g_slider.setEnabled(enabled)
        self.b_slider.setEnabled(enabled)
        
        # 设置复选框状态
        self.invert_checkbox.setEnabled(enabled)
        
        # 设置预处理控件状态
        self.resize_checkbox.setEnabled(enabled)
        self.resize_width_spin.setEnabled(enabled)
        self.resize_height_spin.setEnabled(enabled)
        self.rotate_checkbox.setEnabled(enabled)
        self.rotate_combo.setEnabled(enabled)
        self.flip_h_checkbox.setEnabled(enabled)
        self.flip_v_checkbox.setEnabled(enabled)
        
        # 设置按钮状态
        self.load_button.setEnabled(enabled)
        self.export_bmp_button.setEnabled(enabled)
        self.export_c_button.setEnabled(enabled)
        
        # 设置批处理按钮状态
        self.add_files_button.setEnabled(enabled)
        self.add_dir_button.setEnabled(enabled)
        self.clear_list_button.setEnabled(enabled)
        self.process_batch_button.setEnabled(enabled)
        
    def update_invert_colors(self, state):
        """更新颜色反转设置
        
        Args:
            state (int): 复选框状态
        """
        if not self.image_processor or not self.image_processor.original_image:
            return
            
        # 设置颜色反转状态
        self.image_processor.set_invert_colors(state == Qt.CheckState.Checked.value)
        
        # 禁用UI控件
        self.enable_ui_controls(False)
        
        # 异步处理图像
        self.image_processor.process_image_async()
        
    def update_thresholds(self):
        """更新阈值并重新处理图像"""
        if not self.image_processor or not self.image_processor.original_image:
            return
            
        r_value = self.r_slider.get_value()
        g_value = self.g_slider.get_value()
        b_value = self.b_slider.get_value()
        
        # 更新处理器中的阈值
        self.image_processor.set_thresholds(r_value, g_value, b_value)
        
        # 如果正在处理，则不重复启动
        if self.image_processor.is_busy():
            return
            
        # 禁用UI控件
        self.enable_ui_controls(False)
        
        # 异步处理图像
        self.image_processor.process_image_async()
        
    def load_image(self):
        """加载图片"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择BMP图片", "", "BMP图片 (*.bmp);;所有文件 (*.*)"
        )
        
        if not file_path:
            return
            
        if self.image_processor.load_image(file_path):
            # 更新原始图片显示
            self.original_image_view.set_image(self.image_processor.original_image)
            
            # 禁用UI控件
            self.enable_ui_controls(False)
            
            # 更新状态栏
            self.status_bar.showMessage(f"已加载图片：{os.path.basename(file_path)}")
            
            # 异步处理图像
            self.image_processor.process_image_async()
        else:
            QMessageBox.critical(self, "错误", "无法加载图片，请确保文件格式正确。")
            
    def animate_image_change(self):
        """创建渐变动画效果"""
        # 创建不透明度效果对象
        opacity_effect = QGraphicsOpacityEffect(self.processed_image_view.image_label)
        self.processed_image_view.image_label.setGraphicsEffect(opacity_effect)
        
        # 设置初始不透明度
        opacity_effect.setOpacity(0)
        
        # 使用定时器创建简单动画
        self.animation_timer = QTimer(self)
        self.animation_step = 0
        
        def update_opacity():
            self.animation_step += 1
            opacity = min(1.0, self.animation_step / 10.0)
            opacity_effect.setOpacity(opacity)
            
            if opacity >= 1.0:
                self.animation_timer.stop()
                # 移除效果，避免性能影响
                self.processed_image_view.image_label.setGraphicsEffect(None)
        
        self.animation_timer.timeout.connect(update_opacity)
        self.animation_timer.start(50)  # 50毫秒刷新一次
        
    def export_bmp(self):
        """导出为BMP文件"""
        if not self.image_processor or not self.image_processor.processed_image:
            QMessageBox.warning(self, "警告", "没有可导出的图片，请先加载并处理图片。")
            return
            
        file_path, _ = QFileDialog.getSaveFileName(
            self, "导出BMP", "", "BMP图片 (*.bmp)"
        )
        
        if not file_path:
            return
            
        # 确保文件扩展名正确
        if not file_path.lower().endswith('.bmp'):
            file_path += '.bmp'
            
        if self.image_processor.export_bmp(file_path):
            QMessageBox.information(
                self, "成功", f"图片已成功导出到：{file_path}"
            )
            self.status_bar.showMessage(f"已导出BMP：{os.path.basename(file_path)}")
        else:
            QMessageBox.critical(self, "错误", "导出BMP文件失败。")
            
    def export_c_file(self):
        """导出为C文件"""
        if not self.image_processor or not self.image_processor.processed_image:
            QMessageBox.warning(self, "警告", "没有可导出的图片，请先加载并处理图片。")
            return
            
        file_path, _ = QFileDialog.getSaveFileName(
            self, "导出C文件", "", "C源文件 (*.c)"
        )
        
        if not file_path:
            return
            
        # 确保文件扩展名正确
        if not file_path.lower().endswith('.c'):
            file_path += '.c'
            
        if self.image_processor.export_c_file(file_path):
            QMessageBox.information(
                self, "成功", f"C文件已成功导出到：{file_path}"
            )
            self.status_bar.showMessage(f"已导出C文件：{os.path.basename(file_path)}")
        else:
            QMessageBox.critical(self, "错误", "导出C文件失败。")
            
    def add_batch_files(self):
        """添加文件到批处理列表"""
        file_paths, _ = QFileDialog.getOpenFileNames(
            self, "选择BMP图片", "", "BMP图片 (*.bmp);;所有文件 (*.*)"
        )
        
        if not file_paths:
            return
            
        # 添加文件到列表
        for path in file_paths:
            self.batch_list.addItem(path)
            
        # 更新状态栏
        self.status_bar.showMessage(f"已添加 {len(file_paths)} 个文件到批处理列表")
        
    def add_batch_directory(self):
        """添加目录中的所有BMP文件到批处理列表（包括子目录）"""
        dir_path = QFileDialog.getExistingDirectory(
            self, "选择BMP图片所在目录", ""
        )
        
        if not dir_path:
            return
        
        # 递归扫描目录中的所有BMP文件
        bmp_files = self.scan_directory_for_bmp_files(dir_path)
        
        if not bmp_files:
            QMessageBox.warning(self, "警告", "所选目录中没有找到BMP文件。")
            return
        
        # 添加文件到列表
        for path in bmp_files:
            self.batch_list.addItem(path)
        
        # 更新状态栏
        self.status_bar.showMessage(f"已从目录添加 {len(bmp_files)} 个BMP文件到批处理列表")
    
    def scan_directory_for_bmp_files(self, directory):
        """递归扫描目录及其子目录中的所有BMP文件
        
        Args:
            directory (str): 要扫描的目录路径
            
        Returns:
            list: BMP文件路径列表
        """
        bmp_files = []
        
        try:
            # 遍历目录下的所有项目
            for item in os.listdir(directory):
                item_path = os.path.join(directory, item)
                
                # 如果是文件并且是BMP文件
                if os.path.isfile(item_path) and item_path.lower().endswith('.bmp'):
                    bmp_files.append(item_path)
                
                # 如果是目录，则递归扫描
                elif os.path.isdir(item_path):
                    bmp_files.extend(self.scan_directory_for_bmp_files(item_path))
        except Exception as e:
            print(f"扫描目录失败 {directory}: {str(e)}")
        
        return bmp_files
        
    def clear_batch_files(self):
        """清除批处理列表"""
        self.batch_list.clear()
        self.status_bar.showMessage("已清除批处理列表")
        
    def process_batch(self):
        """开始批量处理图像"""
        # 获取批处理列表中的所有文件
        file_paths = []
        for i in range(self.batch_list.count()):
            file_paths.append(self.batch_list.item(i).text())
            
        if not file_paths:
            QMessageBox.warning(self, "警告", "批处理列表为空，请先添加文件。")
            return
            
        # 禁用UI控件
        self.enable_ui_controls(False)
            
        # 加载图像到处理器
        if self.image_processor.load_images(file_paths):
            # 禁用批量导出按钮
            self.export_batch_button.setEnabled(False)
            
            # 开始异步批处理
            self.image_processor.process_batch_async()
        else:
            QMessageBox.critical(self, "错误", "无法加载图片，请确保文件格式正确。")
            # 启用UI控件
            self.enable_ui_controls(True)
            
    def export_batch(self):
        """批量导出处理后的图像"""
        # 检查是否有处理结果
        if not self.image_processor.get_batch_results():
            QMessageBox.warning(self, "警告", "没有可导出的图片，请先进行批量处理。")
            return
            
        # 创建导出对话框
        export_dialog = QDialog(self)
        export_dialog.setWindowTitle("批量导出")
        export_dialog.setMinimumWidth(400)
        
        # 创建对话框布局
        dialog_layout = QVBoxLayout(export_dialog)
        
        # 提示文字
        info_label = QLabel("请选择导出格式和目录:")
        dialog_layout.addWidget(info_label)
        
        # 选项网格
        options_grid = QGridLayout()
        
        # 选择目录按钮
        dir_label = QLabel("导出目录:")
        options_grid.addWidget(dir_label, 0, 0)
        
        self.export_dir_edit = QLabel("未选择")
        options_grid.addWidget(self.export_dir_edit, 0, 1)
        
        select_dir_button = QPushButton("选择目录")
        select_dir_button.clicked.connect(self.select_export_directory)
        options_grid.addWidget(select_dir_button, 0, 2)
        
        # 导出格式选项
        format_label = QLabel("导出格式:")
        options_grid.addWidget(format_label, 1, 0)
        
        self.export_bmp_checkbox = QCheckBox("BMP格式")
        self.export_bmp_checkbox.setChecked(True)
        options_grid.addWidget(self.export_bmp_checkbox, 1, 1)
        
        self.export_c_checkbox = QCheckBox("C文件")
        options_grid.addWidget(self.export_c_checkbox, 1, 2)
        
        dialog_layout.addLayout(options_grid)
        
        # 按钮区域
        button_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
        )
        button_box.accepted.connect(export_dialog.accept)
        button_box.rejected.connect(export_dialog.reject)
        dialog_layout.addWidget(button_box)
        
        # 执行对话框
        result = export_dialog.exec()
        
        if result == QDialog.DialogCode.Accepted:
            export_dir = self.export_dir_edit.text()
            if export_dir == "未选择":
                QMessageBox.warning(self, "警告", "请选择导出目录。")
                return
                
            export_bmp = self.export_bmp_checkbox.isChecked()
            export_c = self.export_c_checkbox.isChecked()
            
            if not (export_bmp or export_c):
                QMessageBox.warning(self, "警告", "请至少选择一种导出格式。")
                return
                
            # 执行导出
            success_count = 0
            error_count = 0
            
            if export_bmp:
                bmp_result = self.image_processor.export_batch_bmps(export_dir)
                success_count += len(bmp_result["success"])
                error_count += len(bmp_result["failed"])
                
            if export_c:
                c_result = self.image_processor.export_batch_c_files(export_dir)
                success_count += len(c_result["success"])
                error_count += len(c_result["failed"])
                
            # 显示结果
            QMessageBox.information(
                self, "导出完成", 
                f"批量导出完成。\n成功: {success_count}\n失败: {error_count}"
            )
    
    def select_export_directory(self):
        """选择导出目录"""
        dir_path = QFileDialog.getExistingDirectory(
            self, "选择导出目录", ""
        )
        
        if dir_path:
            self.export_dir_edit.setText(dir_path)

    def update_preprocess(self):
        """更新预处理设置并重新处理图像"""
        if not self.image_processor or not self.image_processor.original_image:
            return
            
        # 更新调整大小选项
        resize_enabled = self.resize_checkbox.isChecked()
        resize_width = self.resize_width_spin.value()
        resize_height = self.resize_height_spin.value()
        self.image_processor.set_resize_options(resize_enabled, resize_width, resize_height)
        
        # 更新旋转选项
        rotate_enabled = self.rotate_checkbox.isChecked()
        rotate_angle = self.rotate_combo.currentIndex() * 90  # 0, 90, 180, 270
        self.image_processor.set_rotate_options(rotate_enabled, rotate_angle)
        
        # 更新翻转选项
        flip_h = self.flip_h_checkbox.isChecked()
        flip_v = self.flip_v_checkbox.isChecked()
        self.image_processor.set_flip_options(flip_h, flip_v)
        
        # 如果正在处理，则不重复启动
        if self.image_processor.is_busy():
            return
            
        # 禁用UI控件
        self.enable_ui_controls(False)
        
        # 异步处理图像
        self.image_processor.process_image_async() 